import { Upload } from "@/api/interface/index";
import { Common } from "@/api/config/servicePort";
import http from "@/api";
import SparkMD5 from "spark-md5";
import axios from "axios";

interface UploadParams {
  formData: FormData;
  file: File; // 可选的文件对象
}

interface AliOssConfig {
  multipart: {
    aliosstoken: string;
  };
}

interface AliOssResponseParams {
  key: string;
  policy: string;
  signature: string;
  OSSAccessKeyId: string;
}

/**
 * 计算文件的 MD5 值
 * @param {Blob | File} file - 要计算 MD5 的文件对象
 * @returns {Promise<string>} - 解析为文件的 MD5 值
 */
export function getFileMd5(file): Promise<string> {
  return new Promise((resolve, reject) => {
    let fileReader = new FileReader();

    fileReader.onload = function (event: ProgressEvent<FileReader>) {
      if (event.target && event.target.result) {
        let fileMd5 = SparkMD5.ArrayBuffer.hash(event.target.result);
        resolve(fileMd5);
      } else {
        // 如果 event.target 为 null 或 undefined，或者 result 不存在，则拒绝 Promise
        reject(new Error("Failed to read file content or compute MD5 hash."));
      }
    };

    fileReader.onerror = function (error) {
      // 处理读取文件时的错误
      reject(error);
    };

    fileReader.readAsArrayBuffer(file);
  });
}
const devApiDomain = "http://mallbe.local.com";
/**
 * @name 文件上传模块
 */
// 图片上传
export const newUploadImg = async (params: UploadParams): Promise<{ fileUrl: string }> => {
  const { formData, file } = params;
  console.log(formData, file);

  let OssDomain = "https://colabuy.oss-cn-hangzhou.aliyuncs.com/";

  const configResponse = await http.get<AliOssConfig>("/common/getAliossConfig", {});
  let config = configResponse.data;
  console.log(config);

  let notifyData = {
    size: file.size,
    name: file.name,
    aliosstoken: config.multipart.aliosstoken,
    type: file.type,
    height: 0,
    width: 0,
    md5: ""
  };

  let reader = new FileReader();
  reader.readAsDataURL(file);
  return new Promise((resolve, reject) => {
    reader.onload = async function (e: Event) {
      const readerEvent = e as ProgressEvent<FileReader>;
      const result = readerEvent.target?.result as string;

      if (result) {
        let img = new Image();
        img.src = result;
        img.onload = async function () {
          notifyData.height = img.height;
          notifyData.width = img.width;

          const params = {
            chunk: 0,
            chunksize: 4194304,
            aliosstoken: config.multipart.aliosstoken,
            type: file.type,
            size: file.size,
            name: file.name,
            md5: await getFileMd5(file)
          };

          notifyData.md5 = params.md5;

          const paramsResponse = await http.post<AliOssResponseParams>(devApiDomain + "/addons/alioss/index/params", {
            ...params
          });
          const ossConfig = paramsResponse.data;

          let formDataToSend = new FormData();
          formDataToSend.append("key", ossConfig.key);
          formDataToSend.append("OSSAccessKeyId", ossConfig.OSSAccessKeyId);
          formDataToSend.append("signature", ossConfig.signature);
          formDataToSend.append("policy", ossConfig.policy);
          formDataToSend.append("success_action_status", "200");
          formDataToSend.append("file", file);

          try {
            const uploadResponse = await axios({
              url: OssDomain,
              method: "POST",
              data: formDataToSend,
              withCredentials: false,
              headers: { "Content-Type": "multipart/form-data" }
            });
            console.log(uploadResponse);
            const fullPath = `${OssDomain}${ossConfig.key}`;
            resolve({ fileUrl: fullPath });
          } catch (error) {
            reject(error);
          }
        };
      } else {
        reject(new Error("Failed to read file as data URL."));
      }
    };

    reader.onerror = function (error) {
      reject(new Error(`Error reading file: ${error}`));
    };
  });
};
/**
 * @name 文件上传模块
 */
// 图片上传
export const uploadImg = (params: FormData) => {
  return http.post<Upload.ResFileUrl>(Common + `upload/img`, params, { cancel: false });
};

// 视频上传
export const uploadVideo = (params: FormData) => {
  return http.post<Upload.ResFileUrl>(Common + `/file/upload/video`, params, { cancel: false });
};
